/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.emove.modular.system.controller;

import cn.emove.config.properties.GunsProperties;
import cn.emove.core.common.annotion.BussinessLog;
import cn.emove.core.common.annotion.Permission;
import cn.emove.core.common.constant.Const;
import cn.emove.core.common.constant.dictmap.RoleDict;
import cn.emove.core.common.constant.dictmap.UserDict;
import cn.emove.core.common.constant.factory.ConstantFactory;
import cn.emove.core.common.constant.state.TicketStatus;
import cn.emove.core.common.exception.BizExceptionEnum;
import cn.emove.core.common.page.LayuiPageFactory;
import cn.emove.core.log.LogObjectHolder;
import cn.emove.core.shiro.ShiroKit;
import cn.emove.core.shiro.ShiroUser;
import cn.emove.core.util.ExcelUtil;
import cn.emove.core.util.HttpUtil;
import cn.emove.modular.system.entity.Dict;
import cn.emove.modular.system.entity.TicketEntity;
import cn.emove.modular.system.entity.User;
import cn.emove.modular.system.model.OrderDispatchDto;
import cn.emove.modular.system.model.OrderDto;
import cn.emove.modular.system.model.TicketModel;
import cn.emove.modular.system.service.DictService;
import cn.emove.modular.system.service.TicketService;
import cn.emove.modular.system.service.UserService;
import cn.emove.modular.system.warpper.TicketWrapper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jxl.format.*;
import jxl.write.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统管理员控制器
 *
 * @author fengshuonan
 * @Date 2017年1月11日 下午1:08:17
 */
@Controller
@RequestMapping("/staffTicket")
public class StaffTicketController extends BaseController {

    private static String PREFIX = "/modular/system/staffTicket/";

    @Autowired
    private GunsProperties gunsProperties;

    @Autowired
    private TicketService ticketService;

    @Autowired
    private UserService userService;

    @Autowired
    private DictService dictService;

    /**
     * 跳转到查看管理员列表的页面
     *
     * @author jiaojiaxiang
     * @Date 2019/04/18 10:50
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "staffTicket.html";
    }
    @RequestMapping("/list")
    @Permission
    @ResponseBody
    public Object list(@RequestParam(required = false) String orderNo,
                       @RequestParam(required = false) String contactName ,
                       @RequestParam(required = false) String createTime,
                       @RequestParam(required = false) String type,
                       @RequestParam(required = false) String describes,
                       @RequestParam(required = false) String repairType) {

        //拼接查询条件
        String beginTime = "";
        String endTime = "";
        int orderSource = 2;
        String shopName = "";
        String shopAdr ="";
        if (ToolUtil.isNotEmpty(createTime)) {
            String[] split = createTime.split(" - ");
            beginTime = split[0];
            endTime = split[1];
        }

        Page<Map<String, Object>> tickets = ticketService.selectTickets(null, orderNo,orderSource, beginTime, endTime,contactName, shopName, shopAdr,  type, null, describes,repairType);
        Page wrapped = new TicketWrapper(tickets).wrap();
        return LayuiPageFactory.createPageInfo(wrapped);

    }

    /**
     * 跳转至派单页面
     * @return
     */
    @Permission
    @RequestMapping(value = "/ticket_dispatch")
    public String ticketDispatch(@RequestParam int orderId,String typeName,Model model) {
        if (ToolUtil.isEmpty(orderId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("orderId", orderId);
        return PREFIX + "staffTicket_dispatch.html";
    }

    /**
     * 查询派单的用户下拉框
     * @return
     */
    @RequestMapping("/userData")
    @ResponseBody
    public JSONObject selectServer(){
        List<Map<String,Object>> userList = new ArrayList<Map<String,Object>>();
        userList = userService.selectStaffUser();
        JSONObject ServerJson = new JSONObject();
        for (Map<String,Object> c : userList) {
            ServerJson.put(String.valueOf(c.get("userId")), c.get("name"));
        }
        return ServerJson;
    }

    /**
     * 获取用户电话
     * @param userId
     * @return
     */
    @RequestMapping(value = "/getUserPhone")
    @ResponseBody
    public Object getUserPhone(@RequestParam String userId){
        User user = userService.selectUserById(userId);
        return user;
    }

    @RequestMapping(value = "/dispatchSave")
    @BussinessLog(value = "派单", key = "userId", dict = RoleDict.class)
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public ResponseData dispatchSave(OrderDispatchDto dispatchDto) {
        String ip = dictService.selectByCode("service_intranet_ip").get(0).getDescription();
        String url = ip+"/api/backstage/orderAllocation?orderId="+dispatchDto.getOrderId()+"&userId="+dispatchDto.getUserId();
        String result = HttpUtil.sendGet(url);
        System.out.println(result);
        if(result!=""){
            JSONObject json = JSONObject.parseObject(result);
            String code = String.valueOf(json.get("code"));
            if("200".equals(code)){
                return SUCCESS_TIP;
            }else{
                throw new ServiceException(BizExceptionEnum.SERVER_ERROR);
            }
        }else {
            throw new ServiceException(BizExceptionEnum.SESSION_TIMEOUT);
        }

    }
    /**
     * 跳转到添加工单
     *
     * @author jiaojiaxiang
     *      * @Date 2019/04/18 10:50
     **/
    @RequestMapping(value = "/add")
    public String roleAdd() {
        return PREFIX + "staffTicket_add.html";
    }

    /**
     * 查询商户下拉框
     * @return
     */
    @RequestMapping("/shopData")
    @ResponseBody
    public JSONObject selectShopData(){
        List<Map<String,Object>> userList = new ArrayList<Map<String,Object>>();
        userList = userService.selectShopData();
        JSONObject ServerJson = new JSONObject();
        for (Map<String,Object> c : userList) {
            ServerJson.put(String.valueOf(c.get("shopId")), c.get("shopName"));
        }
        return ServerJson;
    }

    @RequestMapping(value = "/addSave")
    @BussinessLog(value = "保存", key = "shopId", dict = UserDict.class)
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public ResponseData addSave(OrderDto orderDto) {
        ShiroUser shiroUser = ShiroKit.getUserNotNull();
        String userId = shiroUser.getId();
        orderDto.setCreateUser(userId);
        String ip = dictService.selectByCode("service_intranet_ip").get(0).getDescription();
        String url = ip+"/api/backstage/backstageOrderSave";
        String param = JSON.toJSONString(orderDto);
        String result = HttpUtil.post(url,param);
        System.out.println(result);
        if(result!=""){
            JSONObject json = JSONObject.parseObject(result);
            String code = String.valueOf(json.get("code"));
            if("200".equals(code)){
                return SUCCESS_TIP;
            }else{
                throw new ServiceException(BizExceptionEnum.SERVER_ERROR);
            }
        }else {
            throw new ServiceException(BizExceptionEnum.SESSION_TIMEOUT);
        }

    }
    /**
     * 跳转至详情页面
     * @return
     */
    @Permission
    @RequestMapping(value = "/staffTicket_detail")
    public String ticketDetail(@RequestParam int orderId,String typeName,Model model) {
        if (ToolUtil.isEmpty(orderId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("orderId", orderId);
        model.addAttribute("typeName", typeName);
        LogObjectHolder.me().set(orderId);
        return PREFIX + "staffTicket_detail.html";
    }
    /**
     * 跳转至处理页面
     * @return
     */
    @Permission
    @RequestMapping(value = "/handle")
    public String cancel(@RequestParam int orderId,Model model) {
        if (ToolUtil.isEmpty(orderId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("orderId", orderId);
        LogObjectHolder.me().set(orderId);
        return PREFIX + "staffTicket_handle.html";
    }

    /**
     * 查询处理方式户下拉框
     * @return
     */
    @RequestMapping("/handleData")
    @ResponseBody
    public JSONObject handleData(@RequestParam int orderId){
        if (ToolUtil.isEmpty(orderId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        boolean hp = ShiroKit.hasPermission("/staffTicket/cancel");
        TicketEntity ticket = ticketService.getById(orderId);
        String type = ticket.getType();
        JSONObject ServerJson = new JSONObject();
        if("1".equals(type)){
            if(hp) {
                ServerJson.put("1", "作废");
            }
            ServerJson.put("4","无法处理");
        }else if("9".equals(type)){
            if(hp){
                ServerJson.put("1","作废");
            }
            ServerJson.put("2","转单");
            ServerJson.put("4","无法处理");
            /*ServerJson.put("3","无需处理");*/
        }
        return ServerJson;
    }

    /**
     * 查询工程工班用户下拉框
     * @return
     */
    /*@RequestMapping("/workUserData")
    @ResponseBody
    public JSONObject workUserData(){
        List<Map<String,Object>> userList = new ArrayList<Map<String,Object>>();
        userList = userService.selectProjectWorkUser();
        JSONObject ServerJson = new JSONObject();
        for (Map<String,Object> c : userList) {
            ServerJson.put(String.valueOf(c.get("userId")), c.get("name"));
        }
        return ServerJson;
    }*/
    @GetMapping(value = "/file")
    public String file() {
        return "file";
    }

    /**
     * 图片上传
     * @return {Result}
     */
    @RequestMapping(value = "/upload", method = {RequestMethod.POST})
    @ResponseBody
    public Object headImg(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
        BASE64Encoder base64Encoder =new BASE64Encoder();
        String base64EncoderImg = file.getOriginalFilename()+","+ base64Encoder.encode(file.getBytes());

        String ip = dictService.selectByCode("service_intranet_ip").get(0).getDescription();
        String url = ip+"/api/upload/uploadPicture";
        JSONObject json = new JSONObject();
        json.put("imgBase64",base64EncoderImg);
        String param = JSON.toJSONString(json);
        String result = HttpUtil.post(url,param);
        System.out.println(result);
        JSONObject resultObject = JSONObject.parseObject(result);
        String data = resultObject.get("data").toString();
        Map<String,Object> map2=new HashMap<>();
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("data",map2);
        map2.put("src",data);
        return map;
    }

    @RequestMapping(value = "/handleSave")
    @BussinessLog(value = "处理", key = "userId", dict = RoleDict.class)
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public ResponseData handleSave(OrderDispatchDto dispatchDto) {
        String handleType = dispatchDto.getHandleType();

        String ip = dictService.selectByCode("service_intranet_ip").get(0).getDescription();
        String url = ip+"/api/backstage/backStageOrderUntreated";
        JSONObject jsonData = new JSONObject();
        ShiroUser shiroUser = ShiroKit.getUserNotNull();
        String userId = shiroUser.getId();
        jsonData.put("updateUserId",userId);
        jsonData.put("userId",dispatchDto.getUserId());
        jsonData.put("orderId",dispatchDto.getOrderId());
        jsonData.put("operationDesc",dispatchDto.getContent());
        String img = "";
        String nohandleImg = dispatchDto.getNohandleImages();
       /* StringBuffer imgsb = new StringBuffer();
        if(nohandleImg!=null&&!"".equals(nohandleImg)){
            for(String s : nohandleImg.split(",")){
                if(!"".equals(s)){
                    imgsb.append(s+",");
                }
            }
        }*/
        if("1".equals(handleType)){
            jsonData.put("type","16");
        }else if("2".equals(handleType)){
            jsonData.put("type","2");
        }else if("3".equals(handleType)){
            jsonData.put("type","3");
        }else if("4".equals(handleType)){
            jsonData.put("type","4");
        }

        jsonData.put("nohandleImages",nohandleImg);
        String param = JSON.toJSONString(jsonData);
        String result = HttpUtil.post(url,param);
        System.out.println(result);
        if(result!=""){
            JSONObject json = JSONObject.parseObject(result);
            String code = String.valueOf(json.get("code"));
            if("200".equals(code)){
                return SUCCESS_TIP;
            }else{
                throw new ServiceException(BizExceptionEnum.SERVER_ERROR);
            }
        }else {
            throw new ServiceException(BizExceptionEnum.SESSION_TIMEOUT);
        }

    }

    /**
     * 查询报修类型下拉框
     * @return
     */
    @RequestMapping("/repairTypeData")
    @ResponseBody
    public JSONObject repairTypeData(){
        List<Dict> dict = dictService.selectByCode("repair_type");
        String repairStr = dict.get(0).getName();
        JSONObject ServerJson = new JSONObject();
        for (String c : repairStr.split(",")) {
            ServerJson.put(c,c);
        }
        return ServerJson;
    }

    /**
     * 导出报表
     * @return
     */
    /*@RequestMapping(value = "/export")
    @ResponseBody
    public List<TicketModel> export(@RequestParam(required = false) int orderSource,
                                    @RequestParam(required = false) String orderNo,
                                    @RequestParam(required = false) String contactName,
                                    @RequestParam(required = false) String shopName,
                                    @RequestParam(required = false) String shopAdr,
                                    @RequestParam(required = false) String createTime,
                                    @RequestParam(required = false) String type,
                                    @RequestParam(required = false) String describes,
                                    @RequestParam(required = false) String repairType) throws Exception {

        //拼接查询条件
        String beginTime = "";
        String endTime = "";

        if (ToolUtil.isNotEmpty(createTime)) {
            String[] split = createTime.split(" - ");
            beginTime = split[0];
            endTime = split[1];
        }
        //Page<Map<String, Object>> tickets = ticketService.selectTickets(null, orderNo, orderSource, beginTime, endTime, contactName,shopName,shopAdr,type,null);
        //获取数据
        List<TicketModel> list = ticketService.selectAllTicket(orderSource,orderNo,beginTime,endTime,contactName,shopName,shopAdr,type,describes,repairType);
        List<TicketModel> mList = new ArrayList<>();
        for (TicketModel data : list) {
            //自定义一个新实体类，定义好要导出来的字段，把遍历出来的数据存放到一个新的list，因为会出现关联表的数据
            TicketModel sellDeal = new TicketModel();
            sellDeal.setOrderNo(data.getOrderNo()+"\t");
            sellDeal.setShopName(data.getShopName());
            sellDeal.setShopAdr(data.getShopAdr());
            sellDeal.setCreateTime(String.valueOf(data.getCreateTime()));
            sellDeal.setTypeName(TicketStatus.getDescription(data.getType()));
            sellDeal.setContactName(data.getContactName());
            if(data.getContactPhone()!=null&&!"".equals(data.getContactPhone())){
                sellDeal.setContactPhone(data.getContactPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
            }
            sellDeal.setDescribes(data.getDescribes()+"\t");
            sellDeal.setOperatorName(ConstantFactory.me().getOperatorName(data.getOperatorId()));
            sellDeal.setRepairType(data.getRepairType());
            if(data.getUpdateTime()!=null){
                sellDeal.setUpdateTime(data.getUpdateTime());
            }
            mList.add(sellDeal);
        }
        return mList;
    }*/
    //样品导出
    @RequestMapping(value = "/export")
    public void exportFile(@RequestParam(required = false) int orderSource,
                           @RequestParam(required = false) String orderNo,
                           @RequestParam(required = false) String contactName,
                           @RequestParam(required = false) String shopName,
                           @RequestParam(required = false) String shopAdr,
                           @RequestParam(required = false) String createTime,
                           @RequestParam(required = false) String type,
                           @RequestParam(required = false) String describes,
                           @RequestParam(required = false) String repairType,
                           HttpServletRequest request,
                           HttpServletResponse response) throws Exception {
        //拼接查询条件
        String beginTime = "";
        String endTime = "";

        if (ToolUtil.isNotEmpty(createTime)) {
            String[] split = createTime.split(" - ");
            beginTime = split[0];
            endTime = split[1];
        }
        List<TicketModel> list = ticketService.selectAllTicket(orderSource,orderNo,beginTime,endTime,contactName,shopName,shopAdr,type,describes,repairType);

        // 生成Excel
        //excel标题
        String[] title={"报事单号","报事人","手机号","报事内容","处理人","报修类型","报事时间","状态","最新时间","报事图片","处理图片"};
        //excel名称
        String fileName = "员工工单.xls";
        //sheet名
        String sheetName = "员工工单";

        WritableWorkbook wb = ExcelUtil.getWorkbook(sheetName, title, list, null);

        //响应到客户端
        try {
            wb.write();
            wb.close();
            ExcelUtil.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            HSSFWorkbook work = new HSSFWorkbook(new FileInputStream("/www/员工工单.xls"));
            work.write(os);
            os.close();
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
        }
    }



}
